package com.lznb.cloud.service.impl;

import com.lznb.cloud.entity.News;
import com.lznb.cloud.entity.NewsCategory;
import com.lznb.cloud.repository.NewsRepository;
import com.lznb.cloud.service.NewsService;
import com.lznb.cloud.utils.JsonResultExt;
import com.lznb.cloud.utils.SQLUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.lznb.cloud.entity.News;
import com.lznb.cloud.entity.NewsCategory;
import com.lznb.cloud.repository.NewsCategoryRepository;
import com.lznb.cloud.service.NewsCategoryService;
import com.lznb.cloud.service.NewsService;
import com.lznb.cloud.utils.JsonResultExt;
import com.lznb.cloud.utils.SQLUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@Service
@CacheConfig(cacheNames="news")
public class NewsServiceImpl implements NewsService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private NewsRepository newsRepository;


    @Override
    @CachePut(key = "#root.caches[0].name + ':' + #p0")
    public News getNews(String newsId) {
        return newsRepository.findOne(newsId);
    }

    @Override
    public JsonResultExt save(News news) {
        JsonResultExt jsonResultExt=new JsonResultExt();
         jsonResultExt.run(jsonResultExt,newsRepository.save(news));
        return jsonResultExt;
    }

    @Override
    @CachePut( key = "#root.caches[0].name + ':' + #p0.newsId")
    public JsonResultExt update(News news) {
        JsonResultExt jsonResultExt=new JsonResultExt();
        jsonResultExt.run(jsonResultExt, newsRepository.saveAndFlush(news));
        return jsonResultExt;
    }

    @Override
    @CacheEvict(key = "#root.caches[0].name + ':' + #p0")
    public JsonResultExt delete(String newsId) {
        JsonResultExt jsonResultExt=new JsonResultExt();
        newsRepository.delete(newsId);
        return jsonResultExt;
    }

    @Override
    public Map findByPage(Integer pageIndex, Integer size,News news,Map<String,String> condition) {
        Sort sort = new Sort(Sort.Direction.ASC, "newsSort").and(new Sort(Sort.Direction.DESC, "updateTime"));
        Pageable pageable = new PageRequest(pageIndex, size, sort);
        Specification<News> specification = this.handleSpeci(news,condition);
        Page<News> list = newsRepository.findAll(specification,pageable);
        Map map=new HashMap();
        map.put("code",0);
        map.put("msg","");
        map.put("count",list.getTotalElements());
        map.put("data",list.getContent());

        return map;
    }

    @Override
    public List<News> findByCategory(String categoryId) {
        return newsRepository.findByCategory(categoryId);
    }
    public void deleteInBatch(Iterable<News> newsIterable) {
         newsRepository.deleteInBatch(newsIterable);
    }


    /***
    * 考查询条件处理<br>
    * @param news {@link News} 查询条件实体
    * @return {@link Specification}
    */
    public Specification<News> handleSpeci(News news,Map<String,String> condition) {
        Specification<News> specification = new Specification<News>() {
            @Override
            public Predicate toPredicate(Root<News> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = SQLUtils.CriteriaSQLExt(root,news,criteriaBuilder,condition);
                if(!StringUtils.isEmpty(news.getCategory())){
                    if(!StringUtils.isEmpty(news.getCategory().getCategoryId())){
                        Join<News,NewsCategory> join = root.join("category", JoinType.INNER);
                        predicates.add(criteriaBuilder.equal(join.get("categoryId"), news.getCategory().getCategoryId()));
                    }
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        return specification;
    }
}
